package cn.edu.scau.cmi.chenyuanying.orm.hibernate;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import cn.edu.scau.cmi.chenyuanying.orm.dao.StudentDAO;
import cn.edu.scau.cmi.chenyuanying.orm.dao.TeacherDAO;
import cn.edu.scau.cmi.chenyuanying.orm.domain.Student;
import cn.edu.scau.cmi.chenyuanying.orm.domain.Teacher;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;

public class HibernateController implements Initializable {	
	@FXML private TableView<Teacher> teacherTable;
	@FXML private TableColumn<Teacher, Integer> tid;
	@FXML private TableColumn<Teacher, String> tname;
	@FXML private AnchorPane infoTeacherPane;
	@FXML private AnchorPane studentPane;

	@FXML private TableView<Student> sTableInTeacher;
	@FXML private TableColumn<Student, Integer> sidInTeacher;
	@FXML private TableColumn<Student, String> snameInTeacher;
	@FXML private Button delStudentInTeacher;
	@FXML private Button updStudentInTeacher;
	
	@FXML private TableView<Student> studentTable;
	@FXML private TableColumn<Student, Integer> sid;
	@FXML private TableColumn<Student, String> sname;
	@FXML private TableColumn<Student, String> stutor;
	@FXML private AnchorPane infoStudentPane;
	
	@FXML private Text tidText;
	@FXML private Text sidText;
	@FXML private Text tText;
	@FXML private TextField tidField;
	@FXML private TextField tnameField;
	@FXML private Button tConfirmButton;	
	@FXML private Text sText;
	@FXML private TextField sidField;
	@FXML private TextField snameField;
	@FXML private ChoiceBox<String> tutorField;
	@FXML private Button sConfirmButton;
	
	@FXML private Button tadd;
	@FXML private Button tdel;
	@FXML private Button tupd;
	@FXML private Button tshow;
	@FXML private Button sadd;
	@FXML private Button sdel;
	@FXML private Button supd;
	
	@FXML private Tab teacherTab;
	@FXML private Tab studentTab;
	
	private ObservableList<Teacher> tOblist;
	protected TeacherDAO tdao;
	private ObservableList<Student> sOblist;
	protected StudentDAO sdao; 
	private ObservableList<Student> tmpOblist;
	private Teacher t;
	private Student s;
	private boolean isUpdate = false;	
	private String tutorName = null;
	private ObservableList<String> tutors;
	
	public void teacherConfirm(ActionEvent e) {
//		System.out.println(t);
		int id = stringToInt(tidField.getText());
		String name = tnameField.getText();
		if(!isUpdate) {
			t = new Teacher(id, name);
			System.out.println("add: " + t);
			t.setName(name);
			tdao.add(t);
			tOblist.add(t);	
			tutors.add(t.getName());
		} else {
			System.out.println("update: " + t);
//			t = teacherTable.getSelectionModel().getSelectedItem();
			int idx = teacherTable.getSelectionModel().getSelectedIndex();
//			// 修改选择框中的导师姓名
//			for(int i = 0; i < tutors.size(); i++) {
//				if(tutors.get(i).compareTo(t.getName()) == 0) {
//					tutors.set(i, name);
//					break;
//				}
//			}
			t.setName(name);
			// 修改老师TableView中的显示数据
			tOblist.set(idx, t);
			tdao.update(t);
			
		}	
		tidField.clear();
		tnameField.clear();	
		initPane();
	}
	
	public void studentConfirm(ActionEvent e) {
		int id = stringToInt(sidField.getText());
		String name = snameField.getText();
//		if(tutorName == "请选择") tutorName = null;
		int tutorId = 0;
		for(Teacher i : tOblist) {
			if(tutorName == null) break;
			if(i.getName().compareTo(tutorName) == 0) {
				tutorId = i.getId();
				break;
			}
		}
		
		if(!isUpdate) {	
			s = new Student(id, name, tutorId);
			System.out.println("add " + s);
			sdao.add(s);
			sOblist.add(s);	
		} else {
			s.setName(name);
			s.setTutor(tutorId);
			System.out.println("update " + s);
			sdao.update(s);
			for(int i = 0; i < sOblist.size(); i++) {
				Student tmp = sOblist.get(i);
				if(tmp.getId() == s.getId()) {
					sOblist.set(i, s);
					break;
				}
			}
		}	
		sidField.clear();
		snameField.clear();
		tutorField.getSelectionModel().selectFirst();
		
		initPane();
	}
	

	public void delStudent(ActionEvent e) {
	}

	public void updStudent(ActionEvent e) {		
	}
	
	public void initDAO() {
		tdao = new TeacherDAO();
		sdao = new StudentDAO();
	}
	
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		initDAO();
		initTableView();
		tutorField.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
			@Override
			public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
				// TODO Auto-generated method stub
				tutorName = tutors.get(newValue.intValue());
			}			
		});
		List<String> tmp = new ArrayList<String>();
		for(Teacher i : tOblist) {
			tmp.add(i.getName());
		}
		tutors = FXCollections.observableList(tmp);	
		tutorField.setItems(tutors);
		tutorField.getSelectionModel().selectFirst();
		
		initPane();
		initTeacherButton();
		initStudentButton();
	}
	
	private void initPane() {
		// init Pane
		infoTeacherPane.setVisible(false);
		studentPane.setVisible(false);
		infoStudentPane.setVisible(false); 
	}
	
	private void initTeacherButton() {
		// init button
		// add a teacher
		tadd.setOnAction((ActionEvent e)->{
			isUpdate = false;
			tidField.setVisible(true);
			tidText.setVisible(true);
			tidField.clear();
			tnameField.clear();
			tText.setText("输入要增加的老师信息");
			studentPane.setVisible(false);
			infoTeacherPane.setVisible(true);
		});
		// delete the chosen teacher
		tdel.setOnAction((ActionEvent e)->{
			t = teacherTable.getSelectionModel().getSelectedItem();
			if(t != null) {
				tdao.delete(t.getId());
				tOblist.remove(t);
				for(int i = 0; i < tutors.size(); i++) {
					if(tutors.get(i).compareTo(t.getName()) == 0) {
						tutors.remove(i);
						break;
					}
				}
			}
		});		
		// update the chosen teacher
		tupd.setOnAction((ActionEvent e)->{
			tidField.setVisible(false);
			tidText.setVisible(false);
			t = teacherTable.getSelectionModel().getSelectedItem();
			isUpdate = true;
			if(t != null) {
				tidField.setText(((Integer)t.getId()).toString());
				tnameField.setText(t.getName());
				tText.setText("输入要修改的老师信息");
				studentPane.setVisible(false);
				infoTeacherPane.setVisible(true);				
			}			
		});
		// show student lists of the chosen teacher
		tshow.setOnAction((ActionEvent e)->{
			t = teacherTable.getSelectionModel().getSelectedItem();
			if(t != null) {
				List<Student> tmp = sdao.findByProperty("tutor", ((Integer)t.getId()).toString());
				tmpOblist = FXCollections.observableList(tmp);
				sTableInTeacher.setItems(tmpOblist);
			}
			infoTeacherPane.setVisible(false);
			studentPane.setVisible(true);
		});
	}
	
	private void initStudentButton() {
		// init button
		// add a student
		sadd.setOnAction((ActionEvent e)->{
			isUpdate = false;
			sidField.setVisible(true);
			sidText.setVisible(true);
			sidField.clear();
			snameField.clear();
			
			initChoiceBox();
			sText.setText("输入要增加的学生信息");
			infoStudentPane.setVisible(true);
		});
		// delete the chosen student
		sdel.setOnAction((ActionEvent e)->{
			s = studentTable.getSelectionModel().getSelectedItem();
			System.out.println(s);
			if(s != null) {
				sdao.delete(s.getId());
				sOblist.remove(s);
			}
		});		
		// update the chosen student
		supd.setOnAction((ActionEvent e)->{
			sidField.setVisible(false);
			sidText.setVisible(false);
			initChoiceBox();
			s = studentTable.getSelectionModel().getSelectedItem();
			System.out.println(s);
			
			System.out.println(s == null);
			isUpdate = true;
			if(s != null) {
				System.out.println("update");
				sText.setText("输入要修改的学生信息");
//				tidField.setText(((Integer)t.getId()).toString());
				snameField.setText(s.getName());
				infoStudentPane.setVisible(true);				
			}			
		});		
	}
	
	public void initChoiceBox() {
		List<String> tmp = new ArrayList<String>();
//		tmp.add("请选择");
		for(Teacher i : tOblist) {
			tmp.add(i.getName());
		}
		tutors = FXCollections.observableList(tmp);	
		tutorField.getSelectionModel().selectFirst();
	}
	
	private void initTableView() {
		// init teacher TableView
		List<Teacher> tlist = tdao.findAll();
		tOblist = FXCollections.observableList(tlist);
		tid.setCellValueFactory(new PropertyValueFactory<>("id"));
		tname.setCellValueFactory(new PropertyValueFactory<>("name"));
		teacherTable.setItems(tOblist);
		
		// init student TableView in TeacherTab
		tmpOblist = null;
		sidInTeacher.setCellValueFactory(new PropertyValueFactory<>("id"));
		snameInTeacher.setCellValueFactory(new PropertyValueFactory<>("name"));
		sTableInTeacher.setItems(tmpOblist);		
		
		
		// init student TableView
		List<Student> slist = sdao.findAll();
		sOblist = FXCollections.observableList(slist);
		sid.setCellValueFactory(new PropertyValueFactory<>("id"));
		sname.setCellValueFactory(new PropertyValueFactory<>("name"));
		stutor.setCellValueFactory(new PropertyValueFactory<>("tutor"));
		studentTable.setItems(sOblist);		
		
	}
	
	public int stringToInt(String id) {
		int res = 0;
		for(int i = 0; i < id.length(); i++) {
			res *= 10;
			res += id.charAt(i) - '0';
		}
		return res;
	}

}
